package com.johnny.xia.delayqueue.test1;

import java.util.concurrent.Delayed;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author johnnyxia
 *
 */
public class Student implements Runnable,Delayed{

    private String name;

    private long submitTime;//交卷时间    

    private long workTime;//考试时间    

    public Student(){

    }

    public Student(String name, long submitTime){
        super();
        this.name = name;
        workTime = submitTime;
        /**
         * 将给定单元的时间段转换到此单元。
         * 从较细粒度到较粗粒度的舍位转换，这样会失去精确性。
         * 例如，将 999 毫秒转换为秒的结果为 0。使用参数从较粗粒度到较细粒度转换，如果参数为负，则在数字上溢出至 Long.MIN_VALUE，如果为正，则为 Long.MAX_VALUE。
         * 例如，要将 10 分钟转换为毫秒，请使用：TimeUnit.MILLISECONDS.convert(10L, TimeUnit.MINUTES)
         * 
         */
        //都转为转为ns    
        this.submitTime = TimeUnit.NANOSECONDS.convert(submitTime, TimeUnit.MILLISECONDS) + System.nanoTime();
    }

    @Override
    public void run(){
        System.out.println(name + " 交卷,用时" + workTime / 100 + "分钟");
    }

    @Override
    public long getDelay(TimeUnit unit){
        return unit.convert(submitTime - System.nanoTime(), TimeUnit.NANOSECONDS);
    }

    @Override
    public int compareTo(Delayed o){
        Student that = (Student) o;
        return submitTime > that.submitTime ? 1 : (submitTime < that.submitTime ? -1 : 0);
    }

    public static class EndExam extends Student{

        private ExecutorService exec;

        public EndExam(int submitTime, ExecutorService exec){
            super(null, submitTime);
            this.exec = exec;
        }

        @Override
        public void run(){
            exec.shutdownNow();
        }
    }

}
